
import regeneratorRuntime from './runtime.js';
var app = getApp();
export default {
    connect(url) {
        return new Promise((resolve, reject) => {
            if (!this.socketTask) {
              this.url = url || app.globalData.socketServerHost;
                this.socketTask = wx.connectSocket({
                    url: this.url,
                    header: {
                        'content-type': 'application/json'
                    },
                    method: 'POST',
                    success: ({ errMsg }) => {
                        if (errMsg === 'connectSocket:ok') {
                            resolve();
                        } else {
                            reject(errMsg);
                        }
                    },
                    fail: (err) => {
                        reject(err);
                    },
                });
            } else {
                resolve();
            }
        });
    },
    init(msgCallback) {
        return new Promise((resolve, reject) => {
            if (this.socketTask) {
                this.socketTask.onOpen(res => {
                    console.log('websocket is connected');
                    resolve();
                });
                this.socketTask.onError(err => {
                    console.log('websocket error');
                    console.error(err);
                });
                this.socketTask.onClose(async res => {
                    console.log('websocket is closed');
                    console.log(res);
                    // 1000是正常关闭
                    if (res.code !== 1000) {
                        this.socketTask = null;
                        await this.connect(this.url);
                        await this.init(msgCallback);
                    }
                });
                this.socketTask.onMessage(({ data }) => {
                    data = JSON.parse(data);
                    console.log('收到 socket :', data);
                    msgCallback && msgCallback(data);
                });
            } else {
                reject('init => web socket is null');
            }
        });
    },
    send(data) {
        console.log('发送socket :', data);
        return new Promise((resolve, reject) => {
            if (this.socketTask) {
                this.socketTask.send({
                    data,
                    complete: () => {
                        resolve();
                    },
                });
            } else {
                reject('web socket is null!');
            }
        });
    },
    close() {
        if (this.socketTask) {
            this.socketTask.close();
            delete this.socketTask;
        }
    },
};
